package order

import (
	"context"
	"strconv"
	"strings"

	"mall/common/globalkey"
	"mall/common/jwt"
	"mall/common/resultx"
	"mall/common/utils/pointy"
	"mall/service/forum/api/internal/svc"
	"mall/service/forum/api/internal/types"
	"mall/service/order/rpc/orderclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type RemoveOrderLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewRemoveOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RemoveOrderLogic {
	return &RemoveOrderLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *RemoveOrderLogic) RemoveOrder(
	req *types.RemoveOrderReq,
	headers *[]*types.Header,
) (resp *types.BaseMsgResp, err error) {
	if req.Id == nil || *req.Id == 0 {
		return nil, resultx.NewErrCode(resultx.ORDER_ID_REQUIRED)
	}

	userId := jwt.GetUserId(l.ctx)
	if userId == 0 {
		return nil, resultx.NewErrCode(resultx.TOKEN_EXPIRE_ERROR)
	}

	preload := "order:Id,TradeState"
	var filters []string
	filters = append(filters, "Id,equalTo:"+strconv.FormatInt(int64(*req.Id), 10))
	filters = append(filters, "UserId,equalTo:"+strconv.FormatInt(int64(userId), 10))
	var platformId uint32 = globalkey.ThirdPartyPlatformWechatMini

	res, err := l.svcCtx.OrderRpc.GetOrderById(l.ctx, &orderclient.BaseIdReq{
		Preload:    pointy.GetPointer(preload),
		Filter:     pointy.GetPointer(strings.Join(filters, ";")),
		VisitorId:  pointy.GetPointer(userId),
		PlatformId: pointy.GetPointer(platformId),
	})
	if err != nil {
		logx.Errorw("RemoveOrder GetOrderById err", logx.Field("detail", err.Error()))
		return &types.BaseMsgResp{
			Msg: "操作失败",
		}, nil
	}

	if res == nil || res.Id == nil || *res.Id == 0 {
		return nil, resultx.NewErrCode(resultx.ORDER_PARAM_INVALID)
	}

	if res.TradeState != nil {
		switch *res.TradeState {
		case globalkey.OrderTradeStateUserCancelled, globalkey.OrderTradeStateAutoCancelled, globalkey.OrderTradeStateAdminCancelled:
			_, err = l.svcCtx.OrderRpc.UpdateTradeState(l.ctx, &orderclient.UpdateTradeStateReq{
				Id:         res.Id,
				TradeState: pointy.GetPointer(globalkey.OrderTradeStateUserDeleted),
			})
			if err != nil {
				logx.Errorw("RemoveOrder UpdateTradeState err", logx.Field("detail", err.Error()))
				return &types.BaseMsgResp{
					Msg: "操作失败",
				}, nil
			}
		}

		return &types.BaseMsgResp{
			Msg: "操作成功",
		}, nil
	}

	return &types.BaseMsgResp{}, nil
}
